//
// Created by 花如锦 on 2024/5/12.
//

#include "PointerRef.h"

int PointerRef::GetRefCount(void *Pointer) {
    for (const auto &item: RefCount) {
        if (item.first == Pointer) {
            return item.second;
        }
    }
    return 0;
}

int PointerRef::AddRef(void *Pointer) {
    for(auto iter = RefCount.begin(); iter != RefCount.end(); ++iter){
        if (iter->first && iter->first == Pointer) {
            iter->second = iter->second ++;
            return iter->second;
        } else {
            RefCount.insert(make_pair(Pointer, 1));
        }
    }
    return 0;
}

int PointerRef::DelRef(void *Pointer) {
    for(map<void*, int>::iterator iter = RefCount.begin(); iter != RefCount.end(); ++iter){
        if (iter->first && iter->first == Pointer) {
            iter->second = iter->second --;
            // 如果为0，则从 map 删除
            if (iter->second <= 0) {
                RefCount.erase(iter->first);
                return 0;
            }
            return iter->second;
        }
    }
    return 0;
}

PointerRef *PointerRef::GetInstance() {
    return Ref;
}
